//
//  LMProfileStaticController.m
//  舍品
//
//  Created by 楼 眉 on 16/3/23.
//  Copyright © 2016年 楼 眉. All rights reserved.
//

#import "LMProfileStaticController.h"
#import <YYWebImage.h>
#import <Masonry.h>
#import "LMUser.h"
#import "LMChangeNameController.h"
#import "LMChangeSignController.h"
#import "LMWarningLabel.h"
#import "LMImage.h"
#import "LMWarningLabel.h"
#import "LMProvince.h"

@interface LMProfileStaticController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
/**
 *  头像
 */
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
/**
 *  昵称
 */
@property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
/**
 *  个性签名
 */
@property (weak, nonatomic) IBOutlet UILabel *signLabel;
/**
 *  城市
 */
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
/**
 *  生日
 */
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;
/**
 *  性别
 */
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
/**
 *  日期选择器背景
 */
@property (nonatomic,weak)  UIImageView *bgView;
/**
 *  城市选择器背景
 */
@property (nonatomic,weak)  UIImageView *cityBgView;
/**
 *  地址模型
 */
@property (nonatomic,strong)  NSMutableArray *provinces;
/**
 *  临时存放地址
 */
@property (nonatomic,copy) NSString *tempAddress;
/**
 *  临时存放生日
 */
@property (nonatomic,copy) NSString *tempBirthday;

@end

static    NSString    *const    KUserInformationChange   =   @"userInformationChange";

@implementation LMProfileStaticController

- (NSMutableArray *)provinces
{
    if (_provinces == nil) {
        _provinces = [NSMutableArray array];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"provinces.plist" ofType:nil];
        NSArray *arry = [NSArray arrayWithContentsOfFile:filePath];
        for (NSDictionary *dict in arry) {
            LMProvince *province = [LMProvince provinceWithDict:dict];
            [_provinces addObject:province];
        }
    }
    return _provinces;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCell) name:KUserInformationChange object:nil];
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.tableFooterView = bottomView;
    self.iconImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.iconImageView.clipsToBounds = YES;
    [CALayer LM_RoundedImageWIthImageViewCALayer:_iconImageView.layer Width:_iconImageView.width *kUnit];
    [self setCell];
}
#pragma mark - 给个cell赋值
- (void)setCell
{
    LMUser *user = [LMUser currentUser];
    NSData *imageData = [user.iconImage getData];
    UIImage *iconImage = [UIImage imageWithData:imageData];
    if (iconImage) {
        self.iconImageView.image = iconImage;
    }else
    {
        self.iconImageView.image = [UIImage imageNamed:@"占位图.png"];
    }
    self.nicknameLabel.text = user.nickname;
    
    self.signLabel.text = user.signString;
    self.signLabel.font = [UIFont systemFontOfSize:15];
    self.signLabel.numberOfLines = 0;
    CGSize signLabelSize = [NSString LM_getSizeFromString:user.signString scope:CGSizeMake(self.signLabel.width, 200*kUnit) fontValue:15.0];
    self.signLabel.height = signLabelSize.height;
    
    self.cityLabel.text = user.address;
    self.birthdayLabel.text = user.birthday;
    self.sexLabel.text = user.sex;
    [self.tableView reloadData];
}

#pragma mark - tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self changeIcon];
    };
    if (indexPath.section == 0 && indexPath.row == 1) {
        [self changeNickname];
    }
    if (indexPath.section == 0 && indexPath.row == 2) {
        [self changeSign];
    }
    if (indexPath.section == 0 && indexPath.row == 3) {
              [self changeCity];
    }
    if (indexPath.section == 0 && indexPath.row == 4) {
        [self changeBirthday];
    }
    if (indexPath.section == 0 && indexPath.row == 5) {
        [self changeSex];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ;    if (indexPath.section == 0  && indexPath.row == 0) {
        return 110*kUnit;
    }
    else if (indexPath.section == 0 && indexPath.row == 2)
    {
        if (self.signLabel.height <= 55*kUnit) {
            return 55*kUnit;
        }else
        {
            return self.signLabel.height +10*kUnit;
        }
    }
    else
    {
        return 55*kUnit;
    }
}
#pragma mark - 改生日
/**
 *  加载生日选择器
 */
- (void)changeBirthday
{
    UIImageView *bgView = [[UIImageView alloc]init];
    _bgView = bgView;
    _bgView.hidden = NO;
    _bgView.userInteractionEnabled = YES;
    _bgView.backgroundColor = [UIColor clearColor];
    _bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self.view.window addSubview:_bgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgViewTap)];
    [_bgView addGestureRecognizer:tap];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    NSDateFormatter *ft = [[NSDateFormatter alloc]init];
    [ft setDateFormat:@"yyyy年MM月dd日"];
    NSDate *myDate = [ft dateFromString:[LMUser currentUser].birthday];
    if (myDate) {
        datePicker.date = myDate;
    }
    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    datePicker.backgroundColor = [UIColor whiteColor];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3.5);
    datePicker.y = SCREEN_HEIGHT - datePicker.height;
    [bgView addSubview:datePicker];
    [datePicker addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    [self valueChange:datePicker];

    UIImageView *btnBgView = [[UIImageView alloc]init];
    [bgView addSubview:btnBgView];
    btnBgView.userInteractionEnabled = YES;
    btnBgView.backgroundColor = [UIColor whiteColor];
    [btnBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 44*kUnit));
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(datePicker.mas_top);
    }];
    
    
    UIButton *sureBtn = [[UIButton alloc]init];
    sureBtn.backgroundColor = RGBCOLOR(83, 136, 232);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [btnBgView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH - 10*kUnit*3) / 2, 33*kUnit));
        make.centerY.mas_equalTo(btnBgView);
        make.right.mas_equalTo(btnBgView.mas_right).offset(-10*kUnit);
    }];
    
    UIButton *cancelBtn = [[UIButton alloc]init];
    cancelBtn.backgroundColor = RGBCOLOR(83, 136, 232);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [cancelBtn addTarget:self action:@selector(cancelBtnBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [btnBgView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH - 10*kUnit*3) / 2, 33*kUnit));
        make.centerY.mas_equalTo(btnBgView);
        make.left.mas_equalTo(btnBgView.mas_left).offset(10*kUnit);
    }];
    
}
/**
 *  生日选择器取消按钮
 */
- (void)cancelBtnBtnClick
{
    [self.bgView removeFromSuperview];
}
/**
 *  生日选择器确定按钮
 */
- (void)sureBtnClick
{
    NSString *oldBirthday = [LMUser currentUser].birthday;
    [SVProgressHUD showWithStatus:@"保存中..."];
    LMUser *user = [LMUser currentUser];
    user.birthday = _tempBirthday;
    __weak typeof(self) weakSelf = self;
    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [SVProgressHUD dismiss];
            weakSelf.birthdayLabel.text = _tempBirthday;
            [weakSelf.bgView removeFromSuperview];
        }
        else
        {
            [SVProgressHUD dismiss];
            weakSelf.birthdayLabel.text = oldBirthday;
            user.birthday = oldBirthday;
            [weakSelf.bgView removeFromSuperview];
            [LMWarningLabel LM_createWarningLabelWithTitle:@"保存失败"];
        }
    }];
}
#pragma mark - 背景被点击
- (void)bgViewTap
{
    if (self.bgView) {
        [self.bgView removeFromSuperview];
        self.birthdayLabel.text = [LMUser currentUser].birthday;
    }
    if (_cityBgView) {
        [_cityBgView removeFromSuperview];
    }
}

#pragma mark - 改地址
- (void)changeCity
{
    UIImageView *cityBgView = [[UIImageView alloc]init];
    _cityBgView = cityBgView;
    _cityBgView.hidden = NO;
    _cityBgView.userInteractionEnabled = YES;
    _cityBgView.backgroundColor = [UIColor clearColor];
    _cityBgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self.view.window addSubview:_cityBgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgViewTap)];
    [_cityBgView addGestureRecognizer:tap];
    
    UIPickerView *addressPickerView = [[UIPickerView alloc]init];
    addressPickerView.delegate = self;
    addressPickerView.backgroundColor = [UIColor whiteColor];
    addressPickerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3.5);
    addressPickerView.y = SCREEN_HEIGHT - addressPickerView.height;
    [_cityBgView addSubview:addressPickerView];
    [self pickerView:addressPickerView didSelectRow:0 inComponent:0];
    
    UIImageView *btnBgView = [[UIImageView alloc]init];
    [_cityBgView addSubview:btnBgView];
    btnBgView.userInteractionEnabled = YES;
    btnBgView.backgroundColor = [UIColor whiteColor];
    [btnBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 44*kUnit));
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(addressPickerView.mas_top);
    }];
    
    
    UIButton *citySureBtn = [[UIButton alloc]init];
    citySureBtn.backgroundColor = RGBCOLOR(83, 136, 232);
    [citySureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [citySureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [citySureBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [citySureBtn addTarget:self action:@selector(citySureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [btnBgView addSubview:citySureBtn];
    [citySureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH - 10*kUnit*3) / 2, 33*kUnit));
        make.centerY.mas_equalTo(btnBgView);
        make.right.mas_equalTo(btnBgView.mas_right).offset(-10*kUnit);
    }];
    
    UIButton *cityCancelBtn = [[UIButton alloc]init];
    cityCancelBtn.backgroundColor = RGBCOLOR(83, 136, 232);
    [cityCancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cityCancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cityCancelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [cityCancelBtn addTarget:self action:@selector(cityCancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [btnBgView addSubview:cityCancelBtn];
    [cityCancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH - 10*kUnit*3) / 2, 33*kUnit));
        make.centerY.mas_equalTo(btnBgView);
        make.left.mas_equalTo(btnBgView.mas_left).offset(10*kUnit);
    }];
}

- (void)citySureBtnClick
{
    NSString *oldAddress = [LMUser currentUser].address;
    [SVProgressHUD showWithStatus:@"保存中"];
    LMUser *user = [LMUser currentUser];
    user.address = _tempAddress;
    __weak typeof(self) weakSelf = self;
    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [SVProgressHUD dismiss];
            weakSelf.cityLabel.text = _tempAddress;
            [_cityBgView removeFromSuperview];
        }
        else
        {
            [SVProgressHUD dismiss];
            user.address = oldAddress;
            weakSelf.cityLabel.text = oldAddress;
            [LMWarningLabel LM_createWarningLabelWithTitle:@"保存失败"];
            [_cityBgView removeFromSuperview];
        }
    }];
}

- (void)cityCancelBtnClick
{
    [_cityBgView removeFromSuperview];
}
#pragma mark - 改昵称
- (void)changeNickname
{
    LMChangeNameController *changeNameVc = [[LMChangeNameController alloc]init];
    [self.navigationController pushViewController:changeNameVc animated:YES];
}
#pragma mark - 改签名
- (void)changeSign
{
    LMChangeSignController *signVc = [[LMChangeSignController alloc]init];
    [self.navigationController pushViewController:signVc animated:YES];
}
#pragma mark - 改头像
- (void)changeIcon
{
    if ([AFNetworkReachabilityManager sharedManager].isReachable == NO) {
        [LMWarningLabel LM_createWarningLabelWithTitle:nil];
    }
    else
    {
        __weak typeof(self) weakSelf = self;
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *actionNan = [UIAlertAction actionWithTitle:@"直接拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamera];
    }];
    [alertVc addAction:actionNan];
    
    UIAlertAction *actionNv = [UIAlertAction actionWithTitle:@"从相册取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openAlbum];
    }];
    [alertVc addAction:actionNv];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVc addAction:actionCancel];
    
    [weakSelf presentViewController:alertVc animated:YES completion:nil];
    }
}
#pragma mark - 改性别
- (void)changeSex
{
    if ([AFNetworkReachabilityManager sharedManager].isReachable == 0) {
        [LMWarningLabel LM_createWarningLabelWithTitle:nil];
    }
    else
    {
        LMUser *user = [LMUser currentUser];
        NSString *oldSex = user.sex;
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"修改性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *actionNan = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD showWithStatus:@"保存中"];
        self.sexLabel.text = @"男";
        user.sex = @"男";
        __weak typeof(self) weakSelf = self;
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [SVProgressHUD dismiss];
            }
            else
            {
                [SVProgressHUD dismiss];
                weakSelf.sexLabel.text = oldSex;
                user.sex = oldSex;
                [LMWarningLabel LM_createWarningLabelWithTitle:@"保存失败"];
            }
        }];
    }];
    [alertVc addAction:actionNan];
    
        __weak typeof(self) weakSelf = self;
    UIAlertAction *actionNv = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD showWithStatus:@"保存中"];
        weakSelf.sexLabel.text = @"女";
        user.sex = @"女";
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [SVProgressHUD dismiss];
            }
            else
            {
                [SVProgressHUD dismiss];
                weakSelf.sexLabel.text = oldSex;
                user.sex = oldSex;
                [LMWarningLabel LM_createWarningLabelWithTitle:@"保存失败"];
            }
        }];
    }];
    [alertVc addAction:actionNv];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVc addAction:actionCancel];

    [self presentViewController:alertVc animated:YES completion:nil];
    }
}

#pragma mark - 开启相机
- (void)openCamera
{
    UIImagePickerController *pickerVc = [[UIImagePickerController alloc]init];
    pickerVc.delegate = self;
    pickerVc.allowsEditing = YES;
    pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self presentViewController:pickerVc animated:YES completion:nil];
    
}

#pragma mark - 开启相册
- (void)openAlbum
{
    UIImagePickerController *pickerVc = [[UIImagePickerController alloc]init];
    pickerVc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    pickerVc.delegate = self;
    pickerVc.allowsEditing = YES;
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self presentViewController:pickerVc animated:YES completion:nil];
}
#pragma mark - 取得日期
- (void)valueChange:(id)sender
{
    UIDatePicker *picer = (UIDatePicker *)sender;
    NSDate *myDate = picer.date;
    NSDateFormatter *ft = [[NSDateFormatter alloc]init];
    [ft setDateFormat: @"yyyy年MM月dd日"];
    NSString *dateString = [ft stringFromDate:myDate];
    _tempBirthday = dateString;
}

#pragma mark - UIPickViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-  (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.provinces.count;
    }
    else
    {
        NSInteger index = [pickerView selectedRowInComponent:0];
        LMProvince *province = self.provinces[index];
        return province.cities.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        LMProvince *province = self.provinces[row];
        return province.name;
    }
    else
    {
        NSInteger index = [pickerView selectedRowInComponent:0];
        LMProvince *province = self.provinces[index];
        return province.cities[row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        [pickerView reloadComponent:1];
    }
    NSInteger provinceIndex = [pickerView selectedRowInComponent:0];
    LMProvince *province = self.provinces[provinceIndex];
    
    NSInteger cityIndex = [pickerView selectedRowInComponent:1];
    NSString *cityName = province.cities[cityIndex];
    _tempAddress = [NSString stringWithFormat:@"%@省 %@市",province.name,cityName];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return SCREEN_HEIGHT / 3.5/5;
}

#pragma mark - 从照相或者相册中取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    LMUser *user = [LMUser currentUser];
    AVFile *oldFile = user.iconImage;
    UIImage *oldImage = self.iconImageView.image;
    [SVProgressHUD showWithStatus:@"保存中"];
    //拿到裁剪过的图片
    UIImage *editedImage = info[UIImagePickerControllerEditedImage];
    if (editedImage) {
        //        UIImage *iconImage = [LMImage imageWithImageSimple:editedImage scaledToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH)];
//        NSData *imageData = UIImagePNGRepresentation(editedImage);
        NSData *imageData = UIImagePNGRepresentation(editedImage);
        AVFile *imageFile = [AVFile fileWithData:imageData];
        user.iconImage = imageFile;
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [SVProgressHUD dismiss];
                self.iconImageView.image = editedImage;
                [[NSNotificationCenter defaultCenter] postNotificationName:KUserInformationChange object:nil];
            }
            else
            {
                [SVProgressHUD dismiss];
                self.iconImageView.image = oldImage;
                user.iconImage = oldFile;
                [LMWarningLabel LM_createWarningLabelWithTitle:@"保存失败"];
            }
        }];
    }
    //    [SVProgressHUD dismiss];
    //切出照相机控制器页面
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 隐藏导航控制器
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark - didReceiveMemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - 销毁通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KUserInformationChange object:nil];
    NSLog(@"dealloc--prifleStaticVc");
}
@end
